package com.example.taobao

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.SpannableStringBuilder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_messagedetail.*
import kotlinx.android.synthetic.main.activity_messagedetail.ll_send
import kotlinx.android.synthetic.main.megdetail.*
import kotlinx.android.synthetic.main.myaddress.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.net.URLEncoder
import kotlin.concurrent.thread

class Messagedetail : AppCompatActivity() {
    private var msgdlist: ArrayList<MsgContentBean> = ArrayList<MsgContentBean>()
    private var megpic : String?= String()
    var name111 : String?= String()
    val handle = @SuppressLint("HandlerLeak")
    object : Handler()
    {
        override fun handleMessage(msg: Message) {
            msgdlist.clear()
            msgdlist = msg.obj as ArrayList<MsgContentBean>
            val layoutManager = LinearLayoutManager(this@Messagedetail)
            recyclerview.layoutManager = layoutManager
            val adapter = msgDAdapter(msgdlist)
            if(!msgdlist.isEmpty()) {
                recyclerview.smoothScrollToPosition(msgdlist.size - 1)
            }
            recyclerview.adapter = adapter
            refresh()
        }
    }
    fun refresh()
    {
        val layoutManager = LinearLayoutManager(this@Messagedetail)
        recyclerview.layoutManager = layoutManager
        val adapter = msgDAdapter(msgdlist)
        recyclerview.adapter = adapter
        if(!msgdlist.isEmpty()) {
            recyclerview.smoothScrollToPosition(msgdlist.size - 1)
        }
        adapter.notifyDataSetChanged()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messagedetail)
        var intent = Intent()
        initdata()
        refresh()
        val prefs =  getSharedPreferences("data",Context.MODE_PRIVATE)
        name111 = prefs?.getString("megname","null")
        megpic = prefs!!.getString("megpic","null")
        val username = prefs.getString("name","未登录")
        topname.text = name111
        ll_send.setOnClickListener {
            val gson = Gson()
            msgdlist.add(MsgContentBean(2,et_input.text.toString()))
            val inputString1 = gson.toJson(msgdlist)
            thread {
                try {
                    val client = OkHttpClient()
                    val requestBody = FormBody.Builder()
                        .add("name", URLEncoder.encode(name111,"utf-8"))
                        .add("history", URLEncoder.encode(inputString1,"utf-8"))
                        .add("username", URLEncoder.encode(username,"utf-8"))
                        .build()
                    val request = Request.Builder()
                        .url("http://192.168.43.140:8080/aaa_war_exploded/altermestail.jsp")
                        .post(requestBody)
                        .build()
                    val respone = client.newCall(request).execute()
                    val responeData = respone.body?.string()
                }
                catch (e: java.lang.Exception)
                {
                    e.printStackTrace()
                }
            }
            val editable: Editable = SpannableStringBuilder("")
            et_input.text = editable
            refresh()
        }

        return1.setOnClickListener {
            val intent = Intent()
            intent.setClass(this,zhuyem::class.java)
            intent.putExtra("tag",3)
            startActivity(intent)
        }
        //Toast.makeText(this,name111, Toast.LENGTH_SHORT).show()
    }

    override fun onRestart() {
        super.onRestart()
        initdata()
        refresh()
    }

    private class msgDViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val llRecieve: RelativeLayout = view.findViewById(R.id.rl_receive)
        val llSend: LinearLayout = view.findViewById(R.id.ll_send)
        val rename :TextView = view.findViewById(R.id.tv_nickname_recieve)
        val sename:TextView = view.findViewById(R.id.tv_nickname_send)
        val msgs: TextView = view.findViewById(R.id.tv_msg_send)
        val msgr: TextView = view.findViewById(R.id.tv_msg_receive)
        val tvpic : ImageView =view.findViewById(R.id.iv_avator_recieve)
        val tvpic1 : ImageView =view.findViewById(R.id.iv_avator_send)

    }

    private inner class msgDAdapter(val msgdList: List<MsgContentBean>) :
        RecyclerView.Adapter<msgDViewHolder>() {
        private var itemClickListener: IKotlinItemClickListener? = null
        override fun getItemCount() = msgdList.size
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): msgDViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.megdetail, parent, false)
            return msgDViewHolder(view)
        }
        override fun onBindViewHolder(holder: msgDViewHolder, position: Int) {
            val info = msgdList[position]
            if (msgdList[position].type == 1) {
                holder.llSend.setVerticalGravity(View.GONE)
                holder.llRecieve.setVerticalGravity(View.VISIBLE)
                Glide.with(this@Messagedetail)
                    .load(megpic)
                    .into(holder.tvpic)
                holder.llRecieve.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                holder.llRecieve.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
                holder.rename.text = name111
                holder.llSend.layoutParams.height = 0
                holder.llSend.layoutParams.width = 0
                holder.msgr.text = info.content
            } else if (msgdList[position].type == 2) {
                holder.llSend.setVerticalGravity(View.VISIBLE)
                holder.llRecieve.setVerticalGravity(View.GONE)
                holder.llSend.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                holder.llSend.layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
                holder.llRecieve.layoutParams.height = 0
                holder.llRecieve.layoutParams.width = 0
                holder.sename.text= "Eurus"
                holder.msgs.text = info.content
            }
        }
    }

    fun initdata() {
        thread {
            try {
                var meg :ArrayList<MsgContentBean> = ArrayList<MsgContentBean>()
                val client = OkHttpClient()
                val requestBody = FormBody.Builder()
                    .add("name", URLEncoder.encode(name111, "utf-8"))
                    .add("username", URLEncoder.encode("Eurus", "utf-8"))
                    .build()
                val request = Request.Builder()
                    .url("http://192.168.43.140:8080/aaa_war_exploded/getallmeg1.jsp")
                    .post(requestBody)
                    .build()
                val respone = client.newCall(request).execute()
                val responeData = respone.body!!.string()
                meg = parseJosn(responeData)
                val msg = Message()
                msg.obj = meg
                handle.sendMessage(msg)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun parseJosn(jsonStr:String):ArrayList<MsgContentBean>
    {
        val meg :ArrayList<MsgContentBean> =  ArrayList<MsgContentBean>()
        try {
            val jaonArray = JSONArray(jsonStr)
            for (i in 0 until jaonArray.length())
            {
                val jsonObject = jaonArray.getJSONObject(i)
                val id:Int = jsonObject.getInt("type")
                val content = jsonObject.getString("content")
                meg.add(MsgContentBean(id,content))
            }
        }
        catch (e: Exception)
        {
            e.printStackTrace()
        }
        return meg
    }
}